import React,{useState,useEffect} from 'react';  
import { Row, Col, Steps,Button, message  } from 'antd';  
import './Steps.css'; // 引入自定义的CSS样式文件  
import { ExclamationCircleOutlined, ExclamationCircleFilled } from '@ant-design/icons';  
import LeftItem from './LeftItem'; 
import RightContent from './RightCotent';
import {useTranslation} from 'react-i18next'
import FullscreenLoading from '@/components/FullscreenLoading';
import { createReport,editProduct,separatedFm,addFm,editFm,separatedFix,separatedCreateReport,subjectTestResult,updateSubjectTestResult,mixedfm,mixedFix,mixedCreateReport,getRmInciResult,saveSafetyRmInciResult,batchSaveRmInciResult,updateDataResult,uploadRemark,uploadRemarkUpdate,delRemark,refreshResult} from "@/api/modules/jhreport";



const Step4 = ({formData,onUploadSuccess}) => {  
const { t } = useTranslation();
const [activeItem, setActiveItem] = useState(0); // 跟踪激活的左侧列表项索引  
const [newData,setNewData] = useState([])
const [rightContent, setRightContent] = useState({}); // 右侧内容的状态  
const [currentStep, setCurrentStep] = useState(0); // 当前步骤索引 
const [loading, setLoading] = useState(false); 
 // 假设这是步骤的名称数组，您可以根据需要定制每个步骤的名称  
 const stepNames = ['化妆品安全技术规范', 'CIR结论', '毒理学终点评估结论', '企业历史三年最高使用浓度', 'IECIC兜底浓度', '最终结论', '风险物质'];  
  
  useEffect(()=>{
    setLoading(true)
    getRmInciResult(formData.id).then(res=>{
        console.log(res,'res')
        let rawData =res.data.data
        // deepcode ignore CallbackShouldReturn: <please specify a reason of ignoring this>
        rawData.map(item=>{
            let newarr =[]
            item.reference=JSON.parse(item.reference)
            item.remark=JSON.parse(item.remark)
            item.riskSubstance=JSON.parse(item.riskSubstance)
            item.riskReference=JSON.parse(item.riskReference)
            item.riskRemark=JSON.parse(item.riskRemark)
            if(item.data.subclassification.length>0){
                item.data.subclassification.map(k=>{
                    newarr.push({value:k.name+':'+k.value})
                })
                item.data.subclassificationList=[]
                item.data.subclassificationList=newarr
            }
        })
        setNewData(rawData)
        setRightContent(rawData[0])
        setLoading(false)
    })
  },[])

  const upStep4 = (data,status) =>{
    if(status=='success'){
        for(let i=0;i<newData.length;i++){
            if(newData[i].inciCN==data.inciCN){
                newData[i] = data
                setNewData(newData)
                handleItemClick(i)
            }
        }
    }
  }
  const isJsonString = (str) => {  
    try {  
        JSON.parse(str);  
        return true;  
    } catch (e) {  
        return false;  
    }  
}  

  const handleNext = () =>{
    setLoading(true)
    let rawData = newData
    rawData.map(item=>{
        if (!isJsonString(item.reference)) {  
            item.reference = JSON.stringify(item.reference);  
        }  
        if (!isJsonString(item.remark)) {  
            item.remark = JSON.stringify(item.remark);  
        }  
        if (!isJsonString(item.riskSubstance)) {  
            item.riskSubstance = JSON.stringify(item.riskSubstance);  
        }  
        if (!isJsonString(item.riskReference)) {  
            item.riskReference = JSON.stringify(item.riskReference);  
        }  
        if (!isJsonString(item.riskRemark)) {  
            item.riskRemark = JSON.stringify(item.riskRemark);  
        }  
    })
    let error = 0
    rawData.map(i=>{
        if(i.error !==null){
            message.error("有红色感叹号，请确认")
            error=1
            setLoading(false)
        }
    })
    if(error == 0){
        batchSaveRmInciResult(rawData).then(res=>{
            console.log(res,'第四步提交')
            if(res.data.message == '成功'){
                message.success('Success')
                let data = res.data.data
                onUploadSuccess('4',data)
                setLoading(false)
            }
        })
    }
  }
   
  const handleItemClick = (index) => {  
    setActiveItem(index);  
    const selectedItem = newData[index];  
    console.log(selectedItem,'selectedItem')
    setRightContent(selectedItem);  
  }; 
  
  return (  
    <div>
    <FullscreenLoading showLoading={loading} loadingTip="Loading..."/> 
    <div style={{backgroundColor:'white',fontSize:'12px'}}>
        {newData.length > 0 && (
            <Row gutter={[16, 16]}>  
            <Col span={5}>  
            <div style={{backgroundColor:'#F7F7F7',height:'800px',overflow:'auto'}}>
                {newData.map((item, index) => (  
                    <LeftItem  
                    key={index}  
                    {...item}  
                    index={index}  
                    error={item.error} 
                    isActive={index === activeItem}  
                    onClick={() => handleItemClick(index)} // 传递点击处理函数  
                    />  
                ))} 
            </div>
            
            </Col>  
            <Col span={19}>  
                <RightContent rightContent={rightContent} currentStep={currentStep} setCurrentStep={setCurrentStep} stepNames={stepNames}  upStep4={upStep4}/>  
            </Col> 
        </Row>  
    )}
    </div>
  
      {/* 添加按钮 */}  
      <div style={{marginTop:'2%'}}></div>
      <Row justify="center" align="middle">  
        <Col>  
            <Button type="primary" size='small'  onClick={handleNext}>{t('report.Next')}</Button>   
        </Col>  
    </Row>   
     
   </div> 
  )  
};  
  
export default Step4;